package com.ChenYaRou.www.controller;

import com.ChenYaRou.www.constant.JsonBeanConstant;
import com.ChenYaRou.www.dao.RoleDao;
import com.ChenYaRou.www.dao.UserDao;
import com.ChenYaRou.www.dao.impl.RoleDaoImpl;
import com.ChenYaRou.www.dao.impl.UserDaoImpl;
import com.ChenYaRou.www.utils.JsonBean;
import com.ChenYaRou.www.po.Role;
import com.ChenYaRou.www.po.User;
import com.ChenYaRou.www.utils.Secret;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

import static com.ChenYaRou.www.constant.Constant.ACTIVE_USER;
import static com.ChenYaRou.www.constant.False.EMPTY;

/**
 * @ClassName EnrollServletController
 * @Description TODO
 * @Author 86183
 * @Date 2022/4/30 18:27
 * @Version 1.0
 **/
public class EnrollServletController {
    /**
     * 登录操作 登录成功返回用户角色用于设置cookie
     * @param userName
     * @param password
     * @return
     */
    public String enroll(String userName,String password){
        if(userName!=null && !EMPTY.equals(userName.trim()) &&
                password!=null && !EMPTY.equals(password.trim())){
            User user ;
            UserDao userDao=new UserDaoImpl();
            try {
                user = userDao.select(userName);
                if(user!=null && user.getPassword().equals(Secret.turnSecret(password))){
                    if(user.getState().equals(ACTIVE_USER)){
                        RoleDao roleDao=new RoleDaoImpl();
                        Role role=new Role();
                        role.setId(user.getId());
                        role = roleDao.select(role);
                        return JsonBean.generateJson(JsonBeanConstant.GET,JsonBeanConstant.SUCCESS,role);
                    }
                    return JsonBean.operateList(JsonBeanConstant.BANNED,null);
                }
            } catch (NoSuchAlgorithmException  |
                    SQLException | NoSuchFieldException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
            return JsonBean.operateList(JsonBeanConstant.ERROR_INPUT,null);
        }
        return JsonBean.operateList(JsonBeanConstant.FRONT_ERROR,null);
    }
}
